package com.pac.weixin.service.impl;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.common.tools.StringTools;
import com.common.tools.TimeTools;
import com.common.util.ErrorNumber;
import com.common.util.LogicException;
import com.kuanrf.commons.weixin.api.WxKfService;
import com.kuanrf.commons.weixin.common.WxConsts;
import com.kuanrf.commons.weixin.exception.WxErrorException;
import com.kuanrf.commons.weixin.msg.bean.WxMsg;
import com.kuanrf.commons.weixin.msg.custom.bean.WxCustomMsg;
import com.pac.file.bean.FileBean;
import com.pac.file.service.FileService;
import com.pac.questionnaire.dao.QuestionnaireAnswerFileDao;
import com.pac.questionnaire.dao.QuestionnaireDiagnosisDao;
import com.pac.user.UserKeyContent;
import com.pac.weixin.WeiXinKeyContent;
import com.pac.weixin.bean.WxChatBean;
import com.pac.weixin.bean.WxDoctorSelBean;
import com.pac.weixin.dao.WxChatDao;
import com.pac.weixin.service.WxChatService;
import com.pac.weixin.service.WxDoctorSelService;

/**
 * 微信聊天记录service实现
 * 
 * @author lujun.chen
 * @version [版本号, 2015年2月26日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Service(value = "wxChatService")
public class WxChatServiceImpl implements WxChatService {

	private static Logger logger = Logger.getLogger(WxChatServiceImpl.class);

	@Autowired
	private WxChatDao wxChatDao;

	@Autowired
	private QuestionnaireDiagnosisDao questionnaireDiagnosisDao;
	
	@Autowired
	private QuestionnaireAnswerFileDao questionnaireAnswerFileDao;
	
	@Autowired
	private WxDoctorSelService wxDoctorSelService;

	@Autowired
	private FileService fileService;
	
	@Autowired
	private WxKfService wxKfService;

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public String addWxChat(WxChatBean wxChatBean) {
		if (null == wxChatBean) {
			logger.error("添加微信聊天记录出错，参数为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "参数为空");
		}

		if (StringTools.isNull(wxChatBean.getContent())) {
			logger.error("添加微信聊天记录出错，聊天内容为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "聊天内容为空");
		}

		if (StringTools.isNull(wxChatBean.getDirection())) {
			logger.error("添加微信聊天记录出错，数据流向不明");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "数据流向不明");
		}

		if (StringTools.isNull(wxChatBean.getCreateDate())) {
			wxChatBean.setCreateDate(TimeTools.now());
		}

		if (StringTools.isNull(wxChatBean.getState())) {
			wxChatBean.setState(WeiXinKeyContent.WEIXIN_CHAT_STATE_READ_NO);
		}

		return wxChatDao.addWxChat(wxChatBean);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public boolean updateWxChat(WxChatBean wxChatBean) {
		if (null == wxChatBean) {
			logger.error("更新微信聊天记录出错，参数为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "参数为空");
		}

		if (StringTools.isNull(wxChatBean.getId())) {
			logger.error("更新聊天记录出错，记录ID为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "ID为空");
		}

		return wxChatDao.updateWxChat(wxChatBean);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public boolean delWxChat(WxChatBean wxChatBean) {
		if (null == wxChatBean) {
			logger.error("删除微信聊天记录出错，参数为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "参数为空");
		}

		if (StringTools.isNull(wxChatBean.getId())) {
			logger.error("删除微信聊天记录出错，ID为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "ID为空");
		}

		return wxChatDao.delWxChat(wxChatBean);
	}

	@Override
	public List<WxChatBean> queryWxChat(WxChatBean wxChatBean) {
		return wxChatDao.queryWxChat(wxChatBean);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public boolean addChatFromWx(WxMsg wxMsg) {
		try {

			// 获取聊天对象，如果没有，就发给系统管理员
			String userid = UserKeyContent.USER_ID_SYSTEM;
			WxDoctorSelBean wxDoctorSelBean = wxDoctorSelService
					.findWxDoctorSelByOpenid(wxMsg.getFromUserName());
			if (null != wxDoctorSelBean
					&& !StringTools.isNull(wxDoctorSelBean.getUserId())) {
				userid = wxDoctorSelBean.getUserId();
			}

			WxChatBean wxChatBean = new WxChatBean();
			wxChatBean.setOpenId(wxMsg.getFromUserName());
			wxChatBean.setContent(wxMsg.getContent());
			wxChatBean
					.setDirection(WeiXinKeyContent.WEIXIN_CHAT_DIRECTION_WX_PAC);
			wxChatBean.setUserId(userid);
			addWxChat(wxChatBean);
		} catch (LogicException ex) {
			logger.error("添加从微信发过来的聊天记录出错：" + ex.getMessage());
		} catch (Exception ex) {
			logger.error("添加从微信发过来的聊天记录出错：" + ex);
		}
		return true;
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public boolean addChatImgFromWx(WxMsg wxMsg) {
		try {

			// 获取聊天对象，如果没有，就发给系统管理员
			String userid = UserKeyContent.USER_ID_SYSTEM;
			WxDoctorSelBean wxDoctorSelBean = wxDoctorSelService
					.findWxDoctorSelByOpenid(wxMsg.getFromUserName());
			if (null != wxDoctorSelBean
					&& !StringTools.isNull(wxDoctorSelBean.getUserId())) {
				userid = wxDoctorSelBean.getUserId();
			}

			//从微信获取文件，保存在自己的问卷服务器
			String path="weixing/chat/"+TimeTools.now("yyyy")+"/"+TimeTools.now("MM")+"/"+TimeTools.now("dd");
			FileBean fileBean=fileService.uploadFile(wxMsg.getPicUrl(), path);
			

			StringBuffer sbContent=new StringBuffer();
			sbContent.append("<a href='"+fileBean.getPath()+"' target='_blank'>");
			sbContent.append("<img   src='"+fileBean.getPath()+"'width='30px;' height='30px;' />");
			sbContent.append("</a>");
			WxChatBean wxChatBean = new WxChatBean();
			wxChatBean.setOpenId(wxMsg.getFromUserName());
			wxChatBean.setContent(sbContent.toString());
			wxChatBean
					.setDirection(WeiXinKeyContent.WEIXIN_CHAT_DIRECTION_WX_PAC);
			wxChatBean.setUserId(userid);
			addWxChat(wxChatBean);
		} catch (LogicException ex) {
			logger.error("添加从微信发过来的聊天记录出错：" + ex.getMessage());
		} catch (Exception ex) {
			logger.error("添加从微信发过来的聊天记录出错：" + ex);
		}
		return true;
	}

	@Override
	public List<WxChatBean> pacQueryWxChat(WxChatBean wxChatBean) {

		if (null == wxChatBean) {
			return null;
		}

		// 微信->PAC的聊天记录
		wxChatBean.setDirection(WeiXinKeyContent.WEIXIN_CHAT_DIRECTION_WX_PAC);
		// 未读的
		wxChatBean.setState(WeiXinKeyContent.WEIXIN_CHAT_STATE_READ_NO);

		List<WxChatBean> chatList = queryWxChat(wxChatBean);

		// 查出来后修改聊天记录状态
		for (WxChatBean wxchat : chatList) {
			WxChatBean chatU = new WxChatBean();
			chatU.setId(wxchat.getId());
			chatU.setState(WeiXinKeyContent.WEIXIN_CHAT_STATE_READ_YES);
			updateWxChat(chatU);
		}

		return chatList;
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public boolean addChatFromPac(WxChatBean wxChatBean) {

		if (null == wxChatBean) {
			logger.error("添加发往微信的消息出错，参数为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "参数为空");
		}

		if (StringTools.isNull(wxChatBean.getUserId())) {
			logger.error("添加发往微信的消息出错，用户ID为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "用户ID为空");
		}

		if (StringTools.isNull(wxChatBean.getOpenId())) {
			logger.error("添加发往微信的消息出错，微信OpenId为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "微信openId为空");
		}

		//向微信端发送消息
		try {
			WxCustomMsg message =new WxCustomMsg();
			message.setMsgType(WxConsts.CUSTOM_MSG_TEXT);
			message.setContent(wxChatBean.getContent());
			message.setToUser(wxChatBean.getOpenId());
			wxKfService.send(message);
			wxChatBean.setState(WeiXinKeyContent.WEIXIN_CHAT_STATE_READ_YES);
		} catch (WxErrorException ex) {
			wxChatBean.setState(WeiXinKeyContent.WEIXIN_CHAT_STATE_READ_NO);
			logger.error("OpenId:"+wxChatBean.getOpenId()+",向微信端发送消息出错，"+ex);
		}
		catch(Exception ex)
		{
			wxChatBean.setState(WeiXinKeyContent.WEIXIN_CHAT_STATE_READ_NO);
			logger.error("OpenId:"+wxChatBean.getOpenId()+",向微信端发送消息出错，"+ex);
		}

		wxChatBean.setDirection(WeiXinKeyContent.WEIXIN_CHAT_DIRECTION_PAC_WX);

		addWxChat(wxChatBean);

		return true;
	}

}
